<?php

namespace App\HttpController\Admin;

use App\HttpController\BaseController;
use App\Model\AdminsModel;
use App\Model\LoginLogsModel;
use App\Model\ShopsModel;
use App\Utility\ApiToken;
use App\Utility\Captcha;
use App\Utility\ExcelClient;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use Carbon\Carbon;
use EasySwoole\Utility\Hash;
use EasySwoole\Validate\Validate;


class LoginController extends BaseController {
    public function login(){
        $request = $this->request();
        $data = $request->getRequestParam();
        MysqlPool::invoke(function (MysqlObject $db) use($data){
            $validate = new Validate();
            $validate->addColumn('captcha')->required('请填写验证码')->func(function () use($data){
                return (new Captcha())->check($data['captcha'],$data['captchaKey']);
            },'验证码输入错误');
            $adminModel = new AdminsModel($db);
            $user = $adminModel->where('username', $data['username'])->first();
            $validate->addColumn('username')->required('请填写管理员账号')->func(function () use($data,$user){
                return !empty($user);
            },'管理员账户不存在，请联系超级管理员');
            $validate->addColumn('password')->required('请填写密码')->func(function () use($data,$user){
                return Hash::validatePasswordHash($data['password'],$user['password']);
            },'密码输入错误');
            if($this->validate($validate)){
                $token = (new ApiToken())->sessionEncrypt($user['id']);
                //更新登录日期
                $adminModel->update(['id'=>$user['id'],'login_at'=>date('Y-m-d H:i:s',time())]);
                $return = [
                    'userinfo' => ['id' => $user['id'], 'nickname' => $user['nickname']],
                    'token' => $token
                ];
                return $this->writeJson(0,$return,'登录成功，页面即将跳转...');
            } else {
                return $this->writeJson(1, null, $validate->getError()->__toString());
            }
        });
    }


    /**
     * @title 验证码
     * @description 获取验证码信息
     * @method GET
     * @request manage/captcha
     * @return string captcha 验证码图片地址
     * @return string captchaKey 验证码加密key,用于验证验证码是否正确
     */
    public function captcha(){
        $captcha = (new Captcha())->create();
        return $this->writeJson(0,$captcha);
    }

    public function import(){
        $request= $this->request();
        $params   = $request->getRequestParam();
        $list = MysqlPool::invoke(function (MysqlObject $db) use($params){
            $model  = new ShopsModel($db);
            $list = $model->where(function ($query) use($params){
                if($params['start']){
                    $query->whereDate('created_at',$params['start'],'>=');
                }
                if($params['stop']){
                    $query->whereDate('created_at',$params['stop'],'<=');
                }
            })
                ->orderBy('created_at')
                ->get();
            $this->stateToText($list,[
                'status' => $model::STATUS_WORD,
            ]);
            return $list;
        });
        $excel = new ExcelClient();
        //因为swoole有自己的response,header头不允许直接设置,其他框架可以直接用上一个函数
        $name = $excel->download($list);
        //生成文件后，使用response输出
        $this->response()->write(file_get_contents($name));
        $this->response()->withHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $this->response()->withHeader('Content-Disposition', 'attachment;filename='.$name);
        $this->response()->withHeader('Cache-Control','max-age=0');
        $this->response()->end();
    }


    public function download(){
        $list = MysqlPool::invoke(function (MysqlObject $db){
            $model  = new ShopsModel($db);
            //->subMonth()
            $start  = Carbon::now()->firstOfMonth()->toDateString();
            $stop  = Carbon::now()->lastOfMonth()->toDateString();
            $list = $model->whereDate('created_at',$start,'>=')
                ->select('images,imgs,finish_imgs,money_img,order_id')
                ->whereDate('created_at',$stop,'<=')
                ->orderBy('created_at')
                ->get();
            //copy
            return $list;
        });
        $imgs = [];
        foreach ($list as $item){
            $push = [];
            $push = array_merge();
//            $imgs[$item['order_id']][] = $item
        }
        return $this->writeJson(0,$list);

    }
}
